package com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityShedRacePigeonPairBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterShedRacePigeonPair
import com.gexiaobao.pigeon.ui.adapter.MyAdapter
import com.gexiaobao.pigeon.viewmodel.ShedPigeonViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2024/6/12 9:02
 * @Describe    : 公棚某场比赛下赛鸽配对
 */
class ActivityShedRacePigeonPair : BaseActivity<ShedPigeonViewModel, ActivityShedRacePigeonPairBinding>() {

    private val mAdapter: AdapterShedRacePigeonPair by lazy { AdapterShedRacePigeonPair(arrayListOf()) }
    private var mRaceId = 0
    private lateinit var loadsir: LoadService<Any>
    private var ringId = ""
    private var memberName = ""
    private var listPopupWindow: ListPopupWindow? = null
    private val mList: MutableList<String> = mutableListOf()
    private var mSearchType = ""

    override fun initView(savedInstanceState: Bundle?) {
        mSearchType = getString(R.string.search_by_foster)
        mDatabind.includeBar.toolbar.initClose("赛鸽列表") {
            finish()
        }
        mRaceId = intent.getIntExtra("raceId", 0)
        initPopup()
        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            onRefresh(true)
        }
        onRefresh(true)

        mDatabind.layoutList.swipeRefreshLayout.init {
            onRefresh(true)
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, 0))
            it.initFooter {
                //触发加载更多时请求数据
                mViewModel.getLoftPigeonListByRaceId(false, memberName, ringId, mRaceId)
            }
        }

        mDatabind.includeSearch.editQuery.addTextChangedListener {
            mDatabind.includeSearch.ivClose.isVisible = it.toString().isNotEmpty()
        }

        mDatabind.includeSearch.editQuery.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    searchResultData()
                    hideSoftKeyboard(this)
                }

                else -> {}
            }
            false
        }

        val startActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.data != null && it.resultCode == Activity.RESULT_OK) {
                onRefresh(true)
            }
        }

        mAdapter.addChildClickViewIds(R.id.tv_shed_pair)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_shed_pair -> {
                    val intent = Intent(this, ActivityShedPigeonPair::class.java)
                    intent.putExtra("pigeonId", mAdapter.data[position].id)
                    startActivity.launch(intent)
                }
            }
        }

        listPopupWindow?.setOnItemClickListener { _, _, position, _ ->
            mSearchType = mList[position]
            mDatabind.includeSearch.tvSearchType.text = mSearchType
            mList.add(0, mList.removeAt(position))
            listPopupWindow!!.dismiss()
        }

    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeSearch.ivClose, mDatabind.includeSearch.llSearchType, mDatabind.includeSearch.tvSearch) {
            when (it) {
                mDatabind.includeSearch.tvSearch -> {
                    searchResultData()
                }

                mDatabind.includeSearch.llSearchType -> {
                    listPopupWindow?.show()
                }

                mDatabind.includeSearch.ivClose -> {
                    mDatabind.includeSearch.editQuery.setText("")
                    memberName = ""
                    ringId = ""
                    onRefresh(true)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        super.createObserver()
        /** 收鸽清单 */
        mViewModel.receiptPigeonResult.observe(this) {
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }
    }

    private fun searchResultData() {
        if (mSearchType == "搜鸽主") {
            memberName = mDatabind.includeSearch.editQuery.text.toString().trim()
            ringId = ""
        } else {
            ringId = mDatabind.includeSearch.editQuery.text.toString().trim()
            memberName = ""
        }
        onRefresh(true)
    }

    private fun initPopup() {
        mList.add(getString(R.string.search_by_foster))
        mList.add(getString(R.string.search_by_ringId))

        /** 初始化ListPopupWindow，适配 */
        listPopupWindow = ListPopupWindow(this)
        val adapter = MyAdapter(this, mList)
        listPopupWindow?.setAdapter(adapter)
        listPopupWindow?.anchorView = mDatabind.includeSearch.llSearchType//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindow?.width = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.height = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.isModal = true
    }

    private fun onRefresh(b: Boolean) {
        loadsir.showLoading()
        mViewModel.getLoftPigeonListByRaceId(b, memberName, ringId, mRaceId)
    }
}